// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.DataIndex;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.PageSearchFilter;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.Requisition;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.inventory.model.InventoryExchangeVo;
import com.fowo.api.inventory.model.InventoryOutboundVo;
import com.fowo.api.inventory.model.InventoryStorageVo;
import com.fowo.api.inventory.model.PatternEnum;
import com.fowo.api.inventory.model.SimpleInventoryItem;
import com.fowo.api.inventory.model.TargetTypeEnum;
import com.fowo.api.inventory.model.form.InventoryExchangeFormVo;
import com.fowo.api.inventory.model.form.InventoryOutboundFormVo;
import com.fowo.api.inventory.model.form.InventoryStorageFormVo;
import com.fowo.api.inventory.service.InventoryBusinessService;
import com.fowo.api.mapper.RequisitionMapper;
import com.fowo.api.mapper.RequisitionProductMapper;
import com.fowo.api.mapper.WarehouseMapper;
import com.fowo.api.model.requisition.RequisitionAllAOGAction;
import com.fowo.api.model.requisition.RequisitionCommitAndRqtAction;
import com.fowo.api.model.requisition.RequisitionConfirmReceiptAction;
import com.fowo.api.model.requisition.RequisitionConfirmReceiptsAction;
import com.fowo.api.model.requisition.RequisitionConfirmationTransferAction;
import com.fowo.api.model.requisition.RequisitionConfirmationTransfersAction;
import com.fowo.api.model.requisition.RequisitionExcelPo;
import com.fowo.api.model.requisition.RequisitionImportPo;
import com.fowo.api.model.requisition.RequisitionItemVo;
import com.fowo.api.model.requisition.RequisitionNotarizeAction;
import com.fowo.api.model.requisition.RequisitionPresentAction;
import com.fowo.api.model.requisition.RequisitionReferAction;
import com.fowo.api.model.requisition.RequisitionReleaseinventoryAction;
import com.fowo.api.model.requisition.RequisitionRevocationAction;
import com.fowo.api.model.requisition.RequisitionRevocationOrderAction;
import com.fowo.api.model.requisition.RequisitionSearchParamPo;
import com.fowo.api.model.requisition.RequisitionSubmitAndTransferAction;
import com.fowo.api.model.requisition.RequisitionSubmitTransferAction;
import com.fowo.api.model.requisition.RequisitionTjcommitAction;
import com.fowo.api.model.requisition.RequisitionVo;
import com.fowo.api.model.requisition.constant.RequisitionFeePartTypeEnums;
import com.fowo.api.model.requisition.constant.RequisitionStatusEnums;
import com.fowo.api.model.requisition.constant.RequisitionTypeEnums;
import com.fowo.api.model.requisition.product.RequisitionProductItemVo;
import com.fowo.api.model.requisition.product.RequisitionProductItemVoPages;
import com.fowo.api.model.requisition.product.RequisitionProductSearchParamPo;
import com.fowo.api.model.warehouse.WarehouseItemVo;
import com.fowo.api.model.warehouse.WarehouseSearchParamPo;
import com.fowo.api.service.RequisitionProductService;
import com.fowo.api.service.RequisitionService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 调拨单 服务实现基类
 * @author 蜂窝蜜造平台 配置人：李玉娇，吕家傲
 */
@Slf4j
@DataObjectType(Requisition.class)
@DS("ds24")
public class RequisitionBaseServiceImpl
  extends ServiceImpl<RequisitionMapper, Requisition>
  implements RequisitionService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("widName", "w.`name`");
      put("toWidName", "w2.`name`");
      put("createUserName", "su.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected RequisitionService self;

  @Resource
  protected RequisitionProductService requisitionProductService;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  protected WarehouseMapper warehouseMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected RequisitionRevocationOrderAction requisitionRevocationOrderAction;

  @Resource
  protected InventoryBusinessService inventoryBusinessService;

  @Autowired(required = false)
  protected RequisitionReferAction requisitionReferAction;

  @Autowired(required = false)
  protected RequisitionSubmitTransferAction requisitionSubmitTransferAction;

  @Autowired(required = false)
  protected RequisitionConfirmationTransferAction requisitionConfirmationTransferAction;

  @Autowired(required = false)
  protected RequisitionConfirmReceiptAction requisitionConfirmReceiptAction;

  @Autowired(required = false)
  protected RequisitionTjcommitAction requisitionTjcommitAction;

  @Autowired(required = false)
  protected RequisitionNotarizeAction requisitionNotarizeAction;

  @Autowired(required = false)
  protected RequisitionCommitAndRqtAction requisitionCommitAndRqtAction;

  @Autowired(required = false)
  protected RequisitionAllAOGAction requisitionAllAOGAction;

  @Autowired(required = false)
  protected RequisitionReleaseinventoryAction requisitionReleaseinventoryAction;

  @Autowired(required = false)
  protected RequisitionPresentAction requisitionPresentAction;

  @Autowired(required = false)
  protected RequisitionSubmitAndTransferAction requisitionSubmitAndTransferAction;

  @Autowired(required = false)
  protected RequisitionConfirmationTransfersAction requisitionConfirmationTransfersAction;

  @Autowired(required = false)
  protected RequisitionConfirmReceiptsAction requisitionConfirmReceiptsAction;

  @Autowired(required = false)
  protected RequisitionRevocationAction requisitionRevocationAction;

  @Resource
  protected Validator validator;

  /**
   * 创建调拨单
   * @param model 调拨单
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(RequisitionVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    Requisition entity = new Requisition();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getStatus() == null) {
      entity.setStatus("0");
    }

    if (model.getFeePartType() == null) {
      entity.setFeePartType("0");
    }

    if (model.getType() == null) {
      entity.setType("2");
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getRqtSn())) {
      entity.setRqtSn(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "Requisition.rqtSn")
        )
      );
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("调拨单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 调拨单
   */
  protected void updateAllChilds(RequisitionVo model) throws Exception {
    if (model.getRequisitionProduct() != null) {
      requisitionProductService.saveAllByParentRequisition(
        model.getId(),
        model.getRequisitionProduct()
      );
    }
  }

  /**
   * 更新调拨单
   * @param model 调拨单
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(RequisitionVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    Requisition entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("调拨单不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createUser",
      "createTime",
      "lastUpdateTime",
      "lastUpdateUser",
      "type"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新调拨单（带空值）
   * @param model 调拨单
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(RequisitionVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    Requisition entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("调拨单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(Requisition::getWid, model.getWid())
      .set(Requisition::getToWid, model.getToWid())
      .set(Requisition::getLastUpdateTime, model.getLastUpdateTime())
      .set(Requisition::getLastUpdateUser, model.getLastUpdateUser())
      .set(Requisition::getFreightFee, model.getFreightFee())
      .set(Requisition::getOtherFee, model.getOtherFee())
      .set(Requisition::getFeePartType, model.getFeePartType())
      .set(Requisition::getArrivalTime, model.getArrivalTime())
      .set(
        model.getAttachment() != null,
        Requisition::getAttachment,
        JSON.toJSONString(model.getAttachment())
      )
      .setSql(model.getAttachment() == null, "attachment = null")
      .set(Requisition::getRemark, model.getRemark())
      .eq(Requisition::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(RequisitionSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 调拨产品(requisitionProduct) 对应的对象
    RequisitionProductSearchParamPo requisitionProductSearchParam =
      new RequisitionProductSearchParamPo();
    requisitionProductSearchParam.setDisableDataPremissions(true);
    requisitionProductSearchParam.setParentRequisitionInList(ids);
    RequisitionProductMapper localRequisitionProductMapper = ContextHolder
      .getApplicationContext()
      .getBean(RequisitionProductMapper.class);
    requisitionProductSearchParam.applySqlSegments();
    List<Long> requisitionProductIdList =
      localRequisitionProductMapper.searchIds(requisitionProductSearchParam);
    if (!requisitionProductIdList.isEmpty()) {
      RequisitionProductService localRequisitionProductService = ContextHolder
        .getApplicationContext()
        .getBean(RequisitionProductService.class);
      localRequisitionProductService.batchDelete(requisitionProductIdList);
    }
  }

  /**
   * 删除调拨单
   * @param id 调拨单的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除调拨单
   * @param ids 调拨单的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<RequisitionImportPo> excelToImportRow(
    RequisitionImportPo row,
    Integer rowNumber,
    RequisitionVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<RequisitionImportPo> ir = new ImportRow<RequisitionImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<RequisitionImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new RequisitionVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, RequisitionImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getStatus())) {
      vo.setStatus(RequisitionStatusEnums.toValue(row.getStatus()));
      if (vo.getStatus() == null) {
        ir.addError(
          "status",
          "单据状态只能是：“待配货”, “待调拨”, “待收货”, “已完成”, “已撤销”, “待审批”"
        );
      }
    }
    vo.setFreightFee(SheetUtils.tryToDecimal(row.getFreightFee()));
    vo.setOtherFee(SheetUtils.tryToDecimal(row.getOtherFee()));
    if (StringUtils.hasText(row.getFeePartType())) {
      vo.setFeePartType(
        RequisitionFeePartTypeEnums.toValue(row.getFeePartType())
      );
      if (vo.getFeePartType() == null) {
        ir.addError(
          "feePartType",
          "费用分配方式只能是：“不分配”, “按SKU数量”, “按实重”, “按体积”, “ 自定义”"
        );
      }
    }
    if (StringUtils.hasText(row.getType())) {
      vo.setType(RequisitionTypeEnums.toValue(row.getType()));
      if (vo.getType() == null) {
        ir.addError("type", "调拨类型只能是：“简易调拨”, “完整调拨”");
      }
    }
    vo.setArrivalTime(SheetUtils.tryToDateTime(row.getArrivalTime()));
    // 处理关联字段“出库仓库”
    if (
      !SheetUtils.isBlank(row.getWidName()) && SheetUtils.isBlank(row.getWid())
    ) {
      WarehouseSearchParamPo widSearchParam = new WarehouseSearchParamPo();
      widSearchParam.setLimit(2); // 最大只返回二行记录
      widSearchParam.setNameEq(SheetUtils.trim(row.getWidName()));
      widSearchParam.setFinalFilters(new ArrayList<>());
      widSearchParam
        .getFinalFilters()
        .add(
          new PageSearchFilter()
            .setDataIndex(new DataIndex("widType"))
            .setOp("eq")
            .setValue("1")
        );
      widSearchParam.applySqlSegments();
      List<WarehouseItemVo> widMatches = warehouseMapper.search(widSearchParam);
      if (widMatches.size() == 0) {
        ir.addError("widName", "未能在仓库即时库存中找到匹配的数据");
      } else if (widMatches.size() > 1) {
        ir.addError(
          "widName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setWid(widMatches.get(0).getId());
      }
    }
    // 处理关联字段“入库仓库”
    if (
      !SheetUtils.isBlank(row.getToWidName()) &&
      SheetUtils.isBlank(row.getToWid())
    ) {
      WarehouseSearchParamPo toWidSearchParam = new WarehouseSearchParamPo();
      toWidSearchParam.setLimit(2); // 最大只返回二行记录
      toWidSearchParam.setNameEq(SheetUtils.trim(row.getToWidName()));
      toWidSearchParam.setFinalFilters(new ArrayList<>());
      toWidSearchParam
        .getFinalFilters()
        .add(
          new PageSearchFilter()
            .setDataIndex(new DataIndex("widType"))
            .setOp("eq")
            .setValue("1")
        );
      toWidSearchParam.applySqlSegments();
      List<WarehouseItemVo> toWidMatches = warehouseMapper.search(
        toWidSearchParam
      );
      if (toWidMatches.size() == 0) {
        ir.addError("toWidName", "未能在仓库即时库存中找到匹配的数据");
      } else if (toWidMatches.size() > 1) {
        ir.addError(
          "toWidName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setToWid(toWidMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<RequisitionImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<RequisitionImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            RequisitionImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              RequisitionImportPo row,
              AnalysisContext cxt
            ) {
              RequisitionVo vo = new RequisitionVo();
              ImportRow<RequisitionImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<RequisitionImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<RequisitionImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      RequisitionVo vo = new RequisitionVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      // 重建"调拨单号"
      if (
        importTemplate != null &&
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .anyMatch(m ->
            Boolean.TRUE.equals(m.getNeedRecreate()) &&
            "rqtSn".equals(m.getField())
          )
      ) {
        vo.setRqtSn(
          sysSerialService.getNewSerial(
            new NewSerialRequest(null, "Requisition.rqtSn")
          )
        );
      }

      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    RequisitionSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "wid",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((RequisitionItemVo) r).getWidName())
          )
      );
      exportOptions.addFieldMappingOption(
        "toWid",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((RequisitionItemVo) r).getToWidName())
          )
      );
      exportOptions.addFieldMappingOption(
        "status",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> RequisitionStatusEnums.toLabel((String) o))
      );
      exportOptions.addStringFields(
        "rqtSn",
        "widName",
        "toWidName",
        "status",
        "remark"
      );

      String fileName = String.format(
        "调拨单(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<RequisitionExcelPo> items = new ArrayList<RequisitionExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<RequisitionItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<RequisitionItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (RequisitionItemVo item : list) {
        RequisitionExcelPo excel = new RequisitionExcelPo();
        BeanUtils.copyProperties(item, excel);
        excel.setStatus(RequisitionStatusEnums.toLabel(item.getStatus()));

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "调拨单(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(RequisitionExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过调拨单号查询调拨单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByRqtSn(String rqtSn) {
    return this.baseMapper.getIdByRqtSn(rqtSn);
  }

  /**
   * 通过调拨单号查询调拨单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByRqtSn(List<String> list) {
    return this.baseMapper.getIdsByRqtSn(list);
  }

  /**
   * 通过调拨单主键查询调拨单号
   */
  @Override
  public String getRqtSnById(Long id) {
    return this.baseMapper.getRqtSnById(id);
  }

  /**
   * 通过调拨单主键查询调拨单号列表
   */
  @Override
  public List<String> getRqtSnByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getRqtSnByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("rqtSn"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 调拨单的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public RequisitionVo getVoById(Long id) throws Exception {
    RequisitionVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    RequisitionProductSearchParamPo requisitionProductSearchParamPo =
      new RequisitionProductSearchParamPo();
    requisitionProductSearchParamPo.setParentRequisition(id);
    requisitionProductSearchParamPo.getExtendData().put("queryMode", "sub");
    requisitionProductSearchParamPo
      .getExtendData()
      .put("queryParent", "Requisition");
    requisitionProductSearchParamPo.applySqlSegments();
    vo.setRequisitionProduct(
      requisitionProductService.search(requisitionProductSearchParamPo)
    );

    return vo;
  }

  /**
   * 分页查询调拨单
   * @param search 查询条件
   * @return 调拨单分页查询结果
   */
  @Override
  public Page<RequisitionItemVo> pageSearch(RequisitionSearchParamPo search) {
    Page<RequisitionItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(RequisitionItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   */
  protected Page<?> appendWithChild(Page<RequisitionItemVo> pageResult) {
    return appendWithChild(pageResult, null);
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   * @param sort 子表排序
   */
  protected Page<?> appendWithChild(
    Page<RequisitionItemVo> pageResult,
    String sort
  ) {
    if (
      pageResult == null ||
      pageResult.getRecords() == null ||
      pageResult.getRecords().isEmpty()
    ) {
      return pageResult;
    }
    Page<JSONObject> withChildPage = new Page<>(
      pageResult.getCurrent(),
      pageResult.getSize(),
      pageResult.getTotal()
    );
    withChildPage.setRecords(new ArrayList<>());

    RequisitionProductSearchParamPo requisitionProductSearchParamPo =
      new RequisitionProductSearchParamPo();
    requisitionProductSearchParamPo.setSort(sort);
    requisitionProductSearchParamPo.setPageSize(200);
    requisitionProductSearchParamPo.setParentRequisitionInList(
      pageResult
        .getRecords()
        .stream()
        .map(RequisitionItemVo::getId)
        .collect(Collectors.toList())
    );

    Map<String, Page<RequisitionProductItemVoPages>> requisitionProductMaps =
      requisitionProductService.pagesByParentRequisition(
        requisitionProductSearchParamPo
      );

    for (RequisitionItemVo itemVo : pageResult.getRecords()) {
      JSONObject itemJson = (JSONObject) JSONObject.toJSON(itemVo);
      itemJson.put(
        "requisitionProduct",
        requisitionProductMaps.get(itemVo.getId().toString())
      );
      withChildPage.getRecords().add(itemJson);
    }
    return withChildPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 调拨单分页查询结果
   */
  @Override
  public Page<?> pageWithChildSearch(RequisitionSearchParamPo search) {
    return appendWithChild(
      pageSearch(search),
      search.toChildSort("requisitionProduct")
    );
  }

  /**
   * 仅获取子表的查询结果
   * @param parentId 主表编号
   * @param search 查询条件(仅使用分页参数，不处理其它条件)
   * @return
   */
  @Override
  public Page<?> pageOnlyChildSearch(
    Long parentId,
    RequisitionSearchParamPo search
  ) {
    RequisitionSearchParamPo parentSearchParam = new RequisitionSearchParamPo();
    parentSearchParam.setIdEq(parentId);
    List<RequisitionItemVo> parentList = search(parentSearchParam);
    if (parentList.size() > 0) {
      RequisitionItemVo itemVo = parentList.get(0);

      RequisitionProductSearchParamPo requisitionProductSearchParamPo =
        new RequisitionProductSearchParamPo();
      requisitionProductSearchParamPo.setPageSize(search.getPageSize());
      requisitionProductSearchParamPo.setCurrent(search.getCurrent());
      requisitionProductSearchParamPo.setParentRequisition(itemVo.getId());
      return requisitionProductService.pageSearch(
        requisitionProductSearchParamPo
      );
    } else {
      return null;
    }
  }

  /**
   * 调拨单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'RequisitionOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<RequisitionItemVo>> searchOptions(
    RequisitionSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询调拨单
   * @param search 查询条件
   * @return 调拨单列表查询结果
   */
  @Override
  public List<RequisitionItemVo> search(RequisitionSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询调拨单最后更新时间
   * @param search 查询条件
   * @return 调拨单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(RequisitionSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 撤销
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了撤销操作"
  )
  @Override
  public void revocationOrder(Long id) throws Exception {
    if (requisitionRevocationOrderAction == null) {
      throw new Exception("此操作当前不可用");
    }
    requisitionRevocationOrderAction.run(id);
  }

  /**
   * 次品锁定出库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了次品锁定出库操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void lockBadOut(Long id) throws Exception {
    RequisitionVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareLockBadOut(vo);
    inventoryBusinessService.outbound(formVo);
    // 更新成功状态
    Requisition updateStatusEntity = new Requisition();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("1");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 次品锁定出库 的参数
   */
  protected InventoryOutboundFormVo prepareLockBadOut(RequisitionVo vo)
    throws Exception {
    if (!"1".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(RequisitionVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Lock);
    formVo.setFormNum(vo.getRqtSn());
    formVo.setDocumentType("调拨出库");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (RequisitionProductItemVo requisitionProduct : vo.getRequisitionProduct()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(requisitionProduct.getProductId());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String
            .valueOf(requisitionProduct.getDefectiveRqtQuantity())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(requisitionProduct.getDefectiveRqtQuantity())
      );
      outboundItem.setShopId(
        String.valueOf(requisitionProduct.getShopName()).equals("null")
          ? null
          : String.valueOf(requisitionProduct.getShopName())
      );
      outboundItem.setFnSku(
        ObjectUtils.isEmpty(
            requisitionProduct.getFnsku() == null
              ? null
              : requisitionProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(requisitionProduct.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        requisitionProduct.getFromBadWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(requisitionProduct.getDefectiveRqtQuantity())
              .equals("null")
            ? "0"
            : String.valueOf(requisitionProduct.getDefectiveRqtQuantity())
        )
      );
      outboundItem.setBinIds(binIds);
      outboundItem.setFromBinIdsType(TargetTypeEnum.Lock);
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(requisitionProduct.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 良品锁定出库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了良品锁定出库操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void lockGoodOut(Long id) throws Exception {
    RequisitionVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareLockGoodOut(vo);
    inventoryBusinessService.outbound(formVo);
    // 更新成功状态
    Requisition updateStatusEntity = new Requisition();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("1");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 良品锁定出库 的参数
   */
  protected InventoryOutboundFormVo prepareLockGoodOut(RequisitionVo vo)
    throws Exception {
    if (!"1".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(RequisitionVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Lock);
    formVo.setFormNum(vo.getRqtSn());
    formVo.setDocumentType("调拨出库");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (RequisitionProductItemVo requisitionProduct : vo.getRequisitionProduct()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(requisitionProduct.getProductId());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String.valueOf(requisitionProduct.getAvailbleRqtNum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(requisitionProduct.getAvailbleRqtNum())
      );
      outboundItem.setShopId(
        String.valueOf(requisitionProduct.getShopName()).equals("null")
          ? null
          : String.valueOf(requisitionProduct.getShopName())
      );
      outboundItem.setFnSku(
        ObjectUtils.isEmpty(
            requisitionProduct.getFnsku() == null
              ? null
              : requisitionProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(requisitionProduct.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        requisitionProduct.getFromGoodWarehouseBin(),
        Integer.parseInt(
          String.valueOf(requisitionProduct.getAvailbleRqtNum()).equals("null")
            ? "0"
            : String.valueOf(requisitionProduct.getAvailbleRqtNum())
        )
      );
      outboundItem.setBinIds(binIds);
      outboundItem.setFromBinIdsType(TargetTypeEnum.Lock);
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(requisitionProduct.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 次品出库撤销
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了次品出库撤销操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void revocationBadOut(Long id) throws Exception {
    RequisitionVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareRevocationBadOut(vo);
    inventoryBusinessService.outbound(formVo);
    // 更新成功状态
    Requisition updateStatusEntity = new Requisition();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("3");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 次品出库撤销 的参数
   */
  protected InventoryOutboundFormVo prepareRevocationBadOut(RequisitionVo vo)
    throws Exception {
    if (!"3".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(RequisitionVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setOperate("撤消出库");
    formVo.setReverseQtySign(true);
    formVo.setSupportNegative(true);
    formVo.setFrom(TargetTypeEnum.Defect);
    formVo.setFormNum(vo.getRqtSn());
    formVo.setDocumentType("调拨出库");
    if (ObjectUtils.isEmpty(vo.getLastUpdateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getLastUpdateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (RequisitionProductItemVo requisitionProduct : vo.getRequisitionProduct()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(requisitionProduct.getProductId());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String
            .valueOf(requisitionProduct.getDefectiveRqtQuantity())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(requisitionProduct.getDefectiveRqtQuantity())
      );
      outboundItem.setShopId(
        String.valueOf(requisitionProduct.getShopName()).equals("null")
          ? null
          : String.valueOf(requisitionProduct.getShopName())
      );
      outboundItem.setFnSku(
        ObjectUtils.isEmpty(
            requisitionProduct.getFnsku() == null
              ? null
              : requisitionProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(requisitionProduct.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        requisitionProduct.getFromBadWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(requisitionProduct.getDefectiveRqtQuantity())
              .equals("null")
            ? "0"
            : String.valueOf(requisitionProduct.getDefectiveRqtQuantity())
        )
      );
      outboundItem.setBinIds(binIds);
      outboundItem.setFromBinIdsType(TargetTypeEnum.Normal);
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(requisitionProduct.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 良品出库撤销
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了良品出库撤销操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void revocationGoodOut(Long id) throws Exception {
    RequisitionVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareRevocationGoodOut(vo);
    inventoryBusinessService.outbound(formVo);
    // 更新成功状态
    Requisition updateStatusEntity = new Requisition();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("3");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 良品出库撤销 的参数
   */
  protected InventoryOutboundFormVo prepareRevocationGoodOut(RequisitionVo vo)
    throws Exception {
    if (!"3".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(RequisitionVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setOperate("撤消出库");
    formVo.setReverseQtySign(true);
    formVo.setSupportNegative(true);
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getRqtSn());
    formVo.setDocumentType("调拨出库");
    if (ObjectUtils.isEmpty(vo.getLastUpdateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getLastUpdateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (RequisitionProductItemVo requisitionProduct : vo.getRequisitionProduct()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(requisitionProduct.getProductId());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String.valueOf(requisitionProduct.getAvailbleRqtNum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(requisitionProduct.getAvailbleRqtNum())
      );
      outboundItem.setShopId(
        String.valueOf(requisitionProduct.getShopName()).equals("null")
          ? null
          : String.valueOf(requisitionProduct.getShopName())
      );
      outboundItem.setFnSku(
        ObjectUtils.isEmpty(
            requisitionProduct.getFnsku() == null
              ? null
              : requisitionProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(requisitionProduct.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        requisitionProduct.getFromGoodWarehouseBin(),
        Integer.parseInt(
          String.valueOf(requisitionProduct.getAvailbleRqtNum()).equals("null")
            ? "0"
            : String.valueOf(requisitionProduct.getAvailbleRqtNum())
        )
      );
      outboundItem.setBinIds(binIds);
      outboundItem.setFromBinIdsType(TargetTypeEnum.Normal);
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(requisitionProduct.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 次品入库撤销
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了次品入库撤销操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void revocationBadIn(Long id) throws Exception {
    RequisitionVo vo = getVoById(id);
    InventoryStorageFormVo formVo = prepareRevocationBadIn(vo);
    inventoryBusinessService.storage(formVo);
    // 更新成功状态
    Requisition updateStatusEntity = new Requisition();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("3");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 次品入库撤销 的参数
   */
  protected InventoryStorageFormVo prepareRevocationBadIn(RequisitionVo vo)
    throws Exception {
    if (!"3".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryStorageFormVo formVo = new InventoryStorageFormVo();
    if (ReflectUtil.hasField(RequisitionVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setOperate("撤消入库");
    formVo.setReverseQtySign(true);
    formVo.setSupportNegative(true);
    formVo.setTo(TargetTypeEnum.Defect);
    formVo.setFormNum(vo.getRqtSn());
    formVo.setDocumentType("调拨入库");
    if (ObjectUtils.isEmpty(vo.getLastUpdateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getLastUpdateUser().toString());
    if (ObjectUtils.isEmpty(vo.getToWid())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getToWid());
    for (RequisitionProductItemVo requisitionProduct : vo.getRequisitionProduct()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(requisitionProduct.getProductId());
      InventoryStorageVo storageItem = new InventoryStorageVo();
      storageItem.setItem(inventoryItem);
      storageItem.setQty(
        String
            .valueOf(requisitionProduct.getDefectiveRqtQuantity())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(requisitionProduct.getDefectiveRqtQuantity())
      );
      storageItem.setShopId(
        String.valueOf(requisitionProduct.getShopName()).equals("null")
          ? null
          : String.valueOf(requisitionProduct.getShopName())
      );
      storageItem.setFnSku(
        ObjectUtils.isEmpty(
            requisitionProduct.getFnsku() == null
              ? null
              : requisitionProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(requisitionProduct.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        requisitionProduct.getToBadWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(requisitionProduct.getDefectiveRqtQuantity())
              .equals("null")
            ? "0"
            : String.valueOf(requisitionProduct.getDefectiveRqtQuantity())
        )
      );
      storageItem.setBinIds(binIds);
      storageItem.setFromBinIdsType(TargetTypeEnum.Normal);
      storageItem.setCustomId(vo.getId());
      storageItem.setCustomBdId(requisitionProduct.getId());
      formVo.add(storageItem);
    }
    return formVo;
  }

  /**
   * 良品入库撤销
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了良品入库撤销操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void revocationGoodIn(Long id) throws Exception {
    RequisitionVo vo = getVoById(id);
    InventoryStorageFormVo formVo = prepareRevocationGoodIn(vo);
    inventoryBusinessService.storage(formVo);
    // 更新成功状态
    Requisition updateStatusEntity = new Requisition();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("3");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 良品入库撤销 的参数
   */
  protected InventoryStorageFormVo prepareRevocationGoodIn(RequisitionVo vo)
    throws Exception {
    if (!"3".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryStorageFormVo formVo = new InventoryStorageFormVo();
    if (ReflectUtil.hasField(RequisitionVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setOperate("撤消入库");
    formVo.setReverseQtySign(true);
    formVo.setSupportNegative(true);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getRqtSn());
    formVo.setDocumentType("调拨入库");
    if (ObjectUtils.isEmpty(vo.getLastUpdateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getLastUpdateUser().toString());
    if (ObjectUtils.isEmpty(vo.getToWid())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getToWid());
    for (RequisitionProductItemVo requisitionProduct : vo.getRequisitionProduct()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(requisitionProduct.getProductId());
      InventoryStorageVo storageItem = new InventoryStorageVo();
      storageItem.setItem(inventoryItem);
      storageItem.setQty(
        String.valueOf(requisitionProduct.getAvailbleRqtNum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(requisitionProduct.getAvailbleRqtNum())
      );
      storageItem.setShopId(
        String.valueOf(requisitionProduct.getShopName()).equals("null")
          ? null
          : String.valueOf(requisitionProduct.getShopName())
      );
      storageItem.setFnSku(
        ObjectUtils.isEmpty(
            requisitionProduct.getFnsku() == null
              ? null
              : requisitionProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(requisitionProduct.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        requisitionProduct.getToGoodWarehouseBin(),
        Integer.parseInt(
          String.valueOf(requisitionProduct.getAvailbleRqtNum()).equals("null")
            ? "0"
            : String.valueOf(requisitionProduct.getAvailbleRqtNum())
        )
      );
      storageItem.setBinIds(binIds);
      storageItem.setFromBinIdsType(TargetTypeEnum.Normal);
      storageItem.setCustomId(vo.getId());
      storageItem.setCustomBdId(requisitionProduct.getId());
      formVo.add(storageItem);
    }
    return formVo;
  }

  /**
   * 次品出库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了次品出库操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void badOut(Long id) throws Exception {
    RequisitionVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareBadOut(vo);
    inventoryBusinessService.outbound(formVo);
    // 更新成功状态
    Requisition updateStatusEntity = new Requisition();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("1");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 次品出库 的参数
   */
  protected InventoryOutboundFormVo prepareBadOut(RequisitionVo vo)
    throws Exception {
    if (!"1".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(RequisitionVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Defect);
    formVo.setFormNum(vo.getRqtSn());
    formVo.setDocumentType("调拨出库");
    if (ObjectUtils.isEmpty(vo.getLastUpdateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getLastUpdateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (RequisitionProductItemVo requisitionProduct : vo.getRequisitionProduct()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(requisitionProduct.getProductId());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String
            .valueOf(requisitionProduct.getDefectiveRqtQuantity())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(requisitionProduct.getDefectiveRqtQuantity())
      );
      outboundItem.setShopId(
        String.valueOf(requisitionProduct.getShopName()).equals("null")
          ? null
          : String.valueOf(requisitionProduct.getShopName())
      );
      outboundItem.setFnSku(
        ObjectUtils.isEmpty(
            requisitionProduct.getFnsku() == null
              ? null
              : requisitionProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(requisitionProduct.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        requisitionProduct.getFromBadWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(requisitionProduct.getDefectiveRqtQuantity())
              .equals("null")
            ? "0"
            : String.valueOf(requisitionProduct.getDefectiveRqtQuantity())
        )
      );
      outboundItem.setBinIds(binIds);
      outboundItem.setFromBinIdsType(TargetTypeEnum.Normal);
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(requisitionProduct.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 良品出库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了良品出库操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void goodOut(Long id) throws Exception {
    RequisitionVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareGoodOut(vo);
    inventoryBusinessService.outbound(formVo);
    // 更新成功状态
    Requisition updateStatusEntity = new Requisition();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("1");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 良品出库 的参数
   */
  protected InventoryOutboundFormVo prepareGoodOut(RequisitionVo vo)
    throws Exception {
    if (!"1".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(RequisitionVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getRqtSn());
    formVo.setDocumentType("调拨出库");
    if (ObjectUtils.isEmpty(vo.getLastUpdateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getLastUpdateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (RequisitionProductItemVo requisitionProduct : vo.getRequisitionProduct()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(requisitionProduct.getProductId());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String.valueOf(requisitionProduct.getAvailbleRqtNum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(requisitionProduct.getAvailbleRqtNum())
      );
      outboundItem.setShopId(
        String.valueOf(requisitionProduct.getShopName()).equals("null")
          ? null
          : String.valueOf(requisitionProduct.getShopName())
      );
      outboundItem.setFnSku(
        ObjectUtils.isEmpty(
            requisitionProduct.getFnsku() == null
              ? null
              : requisitionProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(requisitionProduct.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        requisitionProduct.getFromGoodWarehouseBin(),
        Integer.parseInt(
          String.valueOf(requisitionProduct.getAvailbleRqtNum()).equals("null")
            ? "0"
            : String.valueOf(requisitionProduct.getAvailbleRqtNum())
        )
      );
      outboundItem.setBinIds(binIds);
      outboundItem.setFromBinIdsType(TargetTypeEnum.Normal);
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(requisitionProduct.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 次品入库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了次品入库操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void badIn(Long id) throws Exception {
    RequisitionVo vo = getVoById(id);
    InventoryStorageFormVo formVo = prepareBadIn(vo);
    inventoryBusinessService.storage(formVo);
    // 更新成功状态
    Requisition updateStatusEntity = new Requisition();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("1");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 次品入库 的参数
   */
  protected InventoryStorageFormVo prepareBadIn(RequisitionVo vo)
    throws Exception {
    if (!"1".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryStorageFormVo formVo = new InventoryStorageFormVo();
    if (ReflectUtil.hasField(RequisitionVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setTo(TargetTypeEnum.Defect);
    formVo.setFormNum(vo.getRqtSn());
    formVo.setDocumentType("调拨入库");
    if (ObjectUtils.isEmpty(vo.getLastUpdateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getLastUpdateUser().toString());
    if (ObjectUtils.isEmpty(vo.getToWid())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getToWid());
    for (RequisitionProductItemVo requisitionProduct : vo.getRequisitionProduct()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(requisitionProduct.getProductId());
      InventoryStorageVo storageItem = new InventoryStorageVo();
      storageItem.setItem(inventoryItem);
      storageItem.setQty(
        String
            .valueOf(requisitionProduct.getDefectiveRqtQuantity())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(requisitionProduct.getDefectiveRqtQuantity())
      );
      storageItem.setShopId(
        String.valueOf(requisitionProduct.getShopName()).equals("null")
          ? null
          : String.valueOf(requisitionProduct.getShopName())
      );
      storageItem.setFnSku(
        ObjectUtils.isEmpty(
            requisitionProduct.getFnsku() == null
              ? null
              : requisitionProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(requisitionProduct.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        requisitionProduct.getToBadWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(requisitionProduct.getDefectiveRqtQuantity())
              .equals("null")
            ? "0"
            : String.valueOf(requisitionProduct.getDefectiveRqtQuantity())
        )
      );
      storageItem.setBinIds(binIds);
      storageItem.setFromBinIdsType(TargetTypeEnum.Normal);
      storageItem.setCustomId(vo.getId());
      storageItem.setCustomBdId(requisitionProduct.getId());
      formVo.add(storageItem);
    }
    return formVo;
  }

  /**
   * 良品入库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了良品入库操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void goodIn(Long id) throws Exception {
    RequisitionVo vo = getVoById(id);
    InventoryStorageFormVo formVo = prepareGoodIn(vo);
    inventoryBusinessService.storage(formVo);
    // 更新成功状态
    Requisition updateStatusEntity = new Requisition();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("1");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 良品入库 的参数
   */
  protected InventoryStorageFormVo prepareGoodIn(RequisitionVo vo)
    throws Exception {
    if (!"1".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryStorageFormVo formVo = new InventoryStorageFormVo();
    if (ReflectUtil.hasField(RequisitionVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getRqtSn());
    formVo.setDocumentType("调拨入库");
    if (ObjectUtils.isEmpty(vo.getLastUpdateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getLastUpdateUser().toString());
    if (ObjectUtils.isEmpty(vo.getToWid())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getToWid());
    for (RequisitionProductItemVo requisitionProduct : vo.getRequisitionProduct()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(requisitionProduct.getProductId());
      InventoryStorageVo storageItem = new InventoryStorageVo();
      storageItem.setItem(inventoryItem);
      storageItem.setQty(
        String.valueOf(requisitionProduct.getAvailbleRqtNum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(requisitionProduct.getAvailbleRqtNum())
      );
      storageItem.setShopId(
        String.valueOf(requisitionProduct.getShopName()).equals("null")
          ? null
          : String.valueOf(requisitionProduct.getShopName())
      );
      storageItem.setFnSku(
        ObjectUtils.isEmpty(
            requisitionProduct.getFnsku() == null
              ? null
              : requisitionProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(requisitionProduct.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        requisitionProduct.getToGoodWarehouseBin(),
        Integer.parseInt(
          String.valueOf(requisitionProduct.getAvailbleRqtNum()).equals("null")
            ? "0"
            : String.valueOf(requisitionProduct.getAvailbleRqtNum())
        )
      );
      storageItem.setBinIds(binIds);
      storageItem.setFromBinIdsType(TargetTypeEnum.Normal);
      storageItem.setCustomId(vo.getId());
      storageItem.setCustomBdId(requisitionProduct.getId());
      formVo.add(storageItem);
    }
    return formVo;
  }

  /**
   * 锁良品库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了锁良品库存操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void lockGoodIinventory(Long id) throws Exception {
    RequisitionVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareLockGoodIinventory(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    Requisition updateStatusEntity = new Requisition();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("0");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 锁良品库存 的参数
   */
  protected InventoryExchangeFormVo prepareLockGoodIinventory(RequisitionVo vo)
    throws Exception {
    if (!"0".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(RequisitionVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Lock);
    formVo.setFormNum(vo.getRqtSn());
    formVo.setDocumentType("调拨锁库存");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getWid());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (RequisitionProductItemVo requisitionProduct : vo.getRequisitionProduct()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(requisitionProduct.getProductId());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String.valueOf(requisitionProduct.getAvailbleRqtNum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(requisitionProduct.getAvailbleRqtNum())
      );
      exchangeItem.setShopId(
        String.valueOf(requisitionProduct.getShopName()).equals("null")
          ? null
          : String.valueOf(requisitionProduct.getShopName())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            requisitionProduct.getFnsku() == null
              ? null
              : requisitionProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(requisitionProduct.getFnsku().trim())
      );
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(requisitionProduct.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 锁仓位良品库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了锁仓位良品库存操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void lockGoodIinventoryBin(Long id) throws Exception {
    RequisitionVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareLockGoodIinventoryBin(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    Requisition updateStatusEntity = new Requisition();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("0");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 锁仓位良品库存 的参数
   */
  protected InventoryExchangeFormVo prepareLockGoodIinventoryBin(
    RequisitionVo vo
  ) throws Exception {
    if (!"0".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(RequisitionVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getRqtSn());
    formVo.setDocumentType("调拨锁库存");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getWid());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (RequisitionProductItemVo requisitionProduct : vo.getRequisitionProduct()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(requisitionProduct.getProductId());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String.valueOf(requisitionProduct.getAvailbleRqtNum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(requisitionProduct.getAvailbleRqtNum())
      );
      exchangeItem.setShopId(
        String.valueOf(requisitionProduct.getShopName()).equals("null")
          ? null
          : String.valueOf(requisitionProduct.getShopName())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            requisitionProduct.getFnsku() == null
              ? null
              : requisitionProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(requisitionProduct.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        requisitionProduct.getFromGoodWarehouseBin(),
        Integer.parseInt(
          String.valueOf(requisitionProduct.getAvailbleRqtNum()).equals("null")
            ? "0"
            : String.valueOf(requisitionProduct.getAvailbleRqtNum())
        )
      );
      exchangeItem.setFromBinIds(binIds);
      Map<Long, Integer> toBinIds = new HashMap<>();
      toBinIds.put(
        requisitionProduct.getFromGoodWarehouseBin(),
        Integer.parseInt(
          String.valueOf(requisitionProduct.getAvailbleRqtNum()).equals("null")
            ? "0"
            : String.valueOf(requisitionProduct.getAvailbleRqtNum())
        )
      );
      exchangeItem.setToBinIds(toBinIds);
      exchangeItem.setFromBinIdsType(TargetTypeEnum.Normal);
      exchangeItem.setToBinIdsType(TargetTypeEnum.Lock);
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(requisitionProduct.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 锁次品库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了锁次品库存操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void lockBadIinventory(Long id) throws Exception {
    RequisitionVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareLockBadIinventory(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    Requisition updateStatusEntity = new Requisition();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("0");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 锁次品库存 的参数
   */
  protected InventoryExchangeFormVo prepareLockBadIinventory(RequisitionVo vo)
    throws Exception {
    if (!"0".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(RequisitionVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Lock);
    formVo.setFormNum(vo.getRqtSn());
    formVo.setDocumentType("调拨锁库存");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getWid());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (RequisitionProductItemVo requisitionProduct : vo.getRequisitionProduct()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(requisitionProduct.getProductId());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String
            .valueOf(requisitionProduct.getDefectiveRqtQuantity())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(requisitionProduct.getDefectiveRqtQuantity())
      );
      exchangeItem.setShopId(
        String.valueOf(requisitionProduct.getShopName()).equals("null")
          ? null
          : String.valueOf(requisitionProduct.getShopName())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            requisitionProduct.getFnsku() == null
              ? null
              : requisitionProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(requisitionProduct.getFnsku().trim())
      );
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(requisitionProduct.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 锁仓位次品库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了锁仓位次品库存操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void lockBadIinventoryBin(Long id) throws Exception {
    RequisitionVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareLockBadIinventoryBin(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    Requisition updateStatusEntity = new Requisition();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("0");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 锁仓位次品库存 的参数
   */
  protected InventoryExchangeFormVo prepareLockBadIinventoryBin(
    RequisitionVo vo
  ) throws Exception {
    if (!"0".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(RequisitionVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getRqtSn());
    formVo.setDocumentType("调拨锁库存");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getWid());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (RequisitionProductItemVo requisitionProduct : vo.getRequisitionProduct()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(requisitionProduct.getProductId());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String
            .valueOf(requisitionProduct.getDefectiveRqtQuantity())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(requisitionProduct.getDefectiveRqtQuantity())
      );
      exchangeItem.setShopId(
        String.valueOf(requisitionProduct.getShopName()).equals("null")
          ? null
          : String.valueOf(requisitionProduct.getShopName())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            requisitionProduct.getFnsku() == null
              ? null
              : requisitionProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(requisitionProduct.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        requisitionProduct.getFromBadWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(requisitionProduct.getDefectiveRqtQuantity())
              .equals("null")
            ? "0"
            : String.valueOf(requisitionProduct.getDefectiveRqtQuantity())
        )
      );
      exchangeItem.setFromBinIds(binIds);
      Map<Long, Integer> toBinIds = new HashMap<>();
      toBinIds.put(
        requisitionProduct.getFromBadWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(requisitionProduct.getDefectiveRqtQuantity())
              .equals("null")
            ? "0"
            : String.valueOf(requisitionProduct.getDefectiveRqtQuantity())
        )
      );
      exchangeItem.setToBinIds(toBinIds);
      exchangeItem.setFromBinIdsType(TargetTypeEnum.Normal);
      exchangeItem.setToBinIdsType(TargetTypeEnum.Lock);
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(requisitionProduct.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 释放良品库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了释放良品库存操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void releaseGoodInventory(Long id) throws Exception {
    RequisitionVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareReleaseGoodInventory(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    Requisition updateStatusEntity = new Requisition();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("1");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 释放良品库存 的参数
   */
  protected InventoryExchangeFormVo prepareReleaseGoodInventory(
    RequisitionVo vo
  ) throws Exception {
    if (!"1".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(RequisitionVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Lock);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getRqtSn());
    formVo.setDocumentType("调拨释放库存");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getWid());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (RequisitionProductItemVo requisitionProduct : vo.getRequisitionProduct()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(requisitionProduct.getProductId());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String.valueOf(requisitionProduct.getAvailbleRqtNum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(requisitionProduct.getAvailbleRqtNum())
      );
      exchangeItem.setShopId(
        String.valueOf(requisitionProduct.getShopName()).equals("null")
          ? null
          : String.valueOf(requisitionProduct.getShopName())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            requisitionProduct.getFnsku() == null
              ? null
              : requisitionProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(requisitionProduct.getFnsku().trim())
      );
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(requisitionProduct.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 释放良品库存仓位
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了释放良品库存仓位操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void releaseGoodInventoryBin(Long id) throws Exception {
    RequisitionVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareReleaseGoodInventoryBin(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    Requisition updateStatusEntity = new Requisition();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("1");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 释放良品库存仓位 的参数
   */
  protected InventoryExchangeFormVo prepareReleaseGoodInventoryBin(
    RequisitionVo vo
  ) throws Exception {
    if (!"1".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(RequisitionVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getRqtSn());
    formVo.setDocumentType("调拨释放库存");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getWid());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (RequisitionProductItemVo requisitionProduct : vo.getRequisitionProduct()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(requisitionProduct.getProductId());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String.valueOf(requisitionProduct.getAvailbleRqtNum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(requisitionProduct.getAvailbleRqtNum())
      );
      exchangeItem.setShopId(
        String.valueOf(requisitionProduct.getShopName()).equals("null")
          ? null
          : String.valueOf(requisitionProduct.getShopName())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            requisitionProduct.getFnsku() == null
              ? null
              : requisitionProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(requisitionProduct.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        requisitionProduct.getFromGoodWarehouseBin(),
        Integer.parseInt(
          String.valueOf(requisitionProduct.getAvailbleRqtNum()).equals("null")
            ? "0"
            : String.valueOf(requisitionProduct.getAvailbleRqtNum())
        )
      );
      exchangeItem.setFromBinIds(binIds);
      Map<Long, Integer> toBinIds = new HashMap<>();
      toBinIds.put(
        requisitionProduct.getFromGoodWarehouseBin(),
        Integer.parseInt(
          String.valueOf(requisitionProduct.getAvailbleRqtNum()).equals("null")
            ? "0"
            : String.valueOf(requisitionProduct.getAvailbleRqtNum())
        )
      );
      exchangeItem.setToBinIds(toBinIds);
      exchangeItem.setFromBinIdsType(TargetTypeEnum.Lock);
      exchangeItem.setToBinIdsType(TargetTypeEnum.Normal);
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(requisitionProduct.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 释放次品库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了释放次品库存操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void releaseBadInventory(Long id) throws Exception {
    RequisitionVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareReleaseBadInventory(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    Requisition updateStatusEntity = new Requisition();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("1");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 释放次品库存 的参数
   */
  protected InventoryExchangeFormVo prepareReleaseBadInventory(
    RequisitionVo vo
  ) throws Exception {
    if (!"1".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(RequisitionVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Lock);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getRqtSn());
    formVo.setDocumentType("调拨释放库存");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getWid());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (RequisitionProductItemVo requisitionProduct : vo.getRequisitionProduct()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(requisitionProduct.getProductId());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String
            .valueOf(requisitionProduct.getDefectiveRqtQuantity())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(requisitionProduct.getDefectiveRqtQuantity())
      );
      exchangeItem.setShopId(
        String.valueOf(requisitionProduct.getShopName()).equals("null")
          ? null
          : String.valueOf(requisitionProduct.getShopName())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            requisitionProduct.getFnsku() == null
              ? null
              : requisitionProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(requisitionProduct.getFnsku().trim())
      );
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(requisitionProduct.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 释放次品库存仓位
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了释放次品库存仓位操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void releaseBadInventoryBin(Long id) throws Exception {
    RequisitionVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareReleaseBadInventoryBin(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    Requisition updateStatusEntity = new Requisition();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("1");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 释放次品库存仓位 的参数
   */
  protected InventoryExchangeFormVo prepareReleaseBadInventoryBin(
    RequisitionVo vo
  ) throws Exception {
    if (!"1".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(RequisitionVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getRqtSn());
    formVo.setDocumentType("调拨释放库存");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getWid());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (RequisitionProductItemVo requisitionProduct : vo.getRequisitionProduct()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(requisitionProduct.getProductId());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String
            .valueOf(requisitionProduct.getDefectiveRqtQuantity())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(requisitionProduct.getDefectiveRqtQuantity())
      );
      exchangeItem.setShopId(
        String.valueOf(requisitionProduct.getShopName()).equals("null")
          ? null
          : String.valueOf(requisitionProduct.getShopName())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            requisitionProduct.getFnsku() == null
              ? null
              : requisitionProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(requisitionProduct.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        requisitionProduct.getFromBadWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(requisitionProduct.getDefectiveRqtQuantity())
              .equals("null")
            ? "0"
            : String.valueOf(requisitionProduct.getDefectiveRqtQuantity())
        )
      );
      exchangeItem.setFromBinIds(binIds);
      Map<Long, Integer> toBinIds = new HashMap<>();
      toBinIds.put(
        requisitionProduct.getFromBadWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(requisitionProduct.getDefectiveRqtQuantity())
              .equals("null")
            ? "0"
            : String.valueOf(requisitionProduct.getDefectiveRqtQuantity())
        )
      );
      exchangeItem.setToBinIds(toBinIds);
      exchangeItem.setFromBinIdsType(TargetTypeEnum.Lock);
      exchangeItem.setToBinIdsType(TargetTypeEnum.Normal);
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(requisitionProduct.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 提交
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了提交操作"
  )
  @Override
  public void refer(Long id) throws Exception {
    if (requisitionReferAction == null) {
      throw new Exception("此操作当前不可用");
    }
    requisitionReferAction.run(id);
  }

  /**
   * 提交并调拨
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了提交并调拨操作"
  )
  @Override
  public void submitTransfer(Long id) throws Exception {
    if (requisitionSubmitTransferAction == null) {
      throw new Exception("此操作当前不可用");
    }
    requisitionSubmitTransferAction.run(id);
  }

  /**
   * 确认调拨
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了确认调拨操作"
  )
  @Override
  public void confirmationTransfer(Long id) throws Exception {
    if (requisitionConfirmationTransferAction == null) {
      throw new Exception("此操作当前不可用");
    }
    requisitionConfirmationTransferAction.run(id);
  }

  /**
   * 确认收货
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了确认收货操作"
  )
  @Override
  public void confirmReceipt(Long id) throws Exception {
    if (requisitionConfirmReceiptAction == null) {
      throw new Exception("此操作当前不可用");
    }
    requisitionConfirmReceiptAction.run(id);
  }

  /**
   * 提交
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了提交操作"
  )
  @Override
  public void tjcommit(List<Long> ids) throws Exception {
    if (requisitionTjcommitAction == null) {
      throw new Exception("此操作当前不可用");
    }
    requisitionTjcommitAction.run(ids);
  }

  /**
   * 确认调拨
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了确认调拨操作"
  )
  @Override
  public void notarize(List<Long> ids) throws Exception {
    if (requisitionNotarizeAction == null) {
      throw new Exception("此操作当前不可用");
    }
    requisitionNotarizeAction.run(ids);
  }

  /**
   * 提交并调拨
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了提交并调拨操作"
  )
  @Override
  public void commitAndRqt(List<Long> ids) throws Exception {
    if (requisitionCommitAndRqtAction == null) {
      throw new Exception("此操作当前不可用");
    }
    requisitionCommitAndRqtAction.run(ids);
  }

  /**
   * 全部到货
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了全部到货操作"
  )
  @Override
  public void allAOG(List<Long> ids) throws Exception {
    if (requisitionAllAOGAction == null) {
      throw new Exception("此操作当前不可用");
    }
    requisitionAllAOGAction.run(ids);
  }

  /**
   * 释放库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了释放库存操作"
  )
  @Override
  public void releaseinventory(List<Long> ids) throws Exception {
    if (requisitionReleaseinventoryAction == null) {
      throw new Exception("此操作当前不可用");
    }
    requisitionReleaseinventoryAction.run(ids);
  }

  /**
   * 提交
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了提交操作"
  )
  @Override
  public void present(Long id) throws Exception {
    if (requisitionPresentAction == null) {
      throw new Exception("此操作当前不可用");
    }
    requisitionPresentAction.run(id);
  }

  /**
   * 提交并调拨
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了提交并调拨操作"
  )
  @Override
  public void submitAndTransfer(Long id) throws Exception {
    if (requisitionSubmitAndTransferAction == null) {
      throw new Exception("此操作当前不可用");
    }
    requisitionSubmitAndTransferAction.run(id);
  }

  /**
   * 确认调拨
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了确认调拨操作"
  )
  @Override
  public void confirmationTransfers(Long id) throws Exception {
    if (requisitionConfirmationTransfersAction == null) {
      throw new Exception("此操作当前不可用");
    }
    requisitionConfirmationTransfersAction.run(id);
  }

  /**
   * 确认收货
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了确认收货操作"
  )
  @Override
  public void confirmReceipts(Long id) throws Exception {
    if (requisitionConfirmReceiptsAction == null) {
      throw new Exception("此操作当前不可用");
    }
    requisitionConfirmReceiptsAction.run(id);
  }

  /**
   * 撤销
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了撤销操作"
  )
  @Override
  public void revocation(Long id) throws Exception {
    if (requisitionRevocationAction == null) {
      throw new Exception("此操作当前不可用");
    }
    requisitionRevocationAction.run(id);
  }

  /**
   * 视图选项卡标题上显示计数
   */

  @Override
  public Map getTabHeaderShowTotal() {
    RequisitionSearchParamPo search = new RequisitionSearchParamPo();
    return MapUtil
      .builder()
      .put("AllRqt", this.baseMapper.allRqtCount(search))
      .put(
        "Goodstobeallocated",
        this.baseMapper.goodstobeallocatedCount(search)
      )
      .put("Tobetransferred", this.baseMapper.tobetransferredCount(search))
      .put("Waitforreceiving", this.baseMapper.waitforreceivingCount(search))
      .put("Completed", this.baseMapper.completedCount(search))
      .put("Undone", this.baseMapper.undoneCount(search))
      .build();
  }

  /**
   * 全部
   */
  @Override
  public List<RequisitionItemVo> allRqt(RequisitionSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.allRqt(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<RequisitionItemVo> allRqtPage(RequisitionSearchParamPo search) {
    Page<RequisitionItemVo> allRqtPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return allRqtPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return allRqtPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    allRqtPage =
      this.baseMapper.allRqtPage(
          search.toPage(this.baseMapper.allRqtCount(search)),
          search
        );
    List<Long> recordIds = allRqtPage
      .getRecords()
      .stream()
      .map(RequisitionItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return allRqtPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return allRqtPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    allRqtPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return allRqtPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 调拨单分页查询结果
   */
  @Override
  public Page<?> allRqtPageWithChildSearch(RequisitionSearchParamPo search) {
    return appendWithChild(
      allRqtPage(search),
      search.toChildSort("requisitionProduct")
    );
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date allRqtLastUpdateTime(RequisitionSearchParamPo search) {
    return this.baseMapper.allRqtLastUpdateTime(search);
  }

  /**
   * 待配货
   */
  @Override
  public List<RequisitionItemVo> goodstobeallocated(
    RequisitionSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.goodstobeallocated(search);
  }

  /**
   * 待配货分页
   */
  @Override
  public Page<RequisitionItemVo> goodstobeallocatedPage(
    RequisitionSearchParamPo search
  ) {
    Page<RequisitionItemVo> goodstobeallocatedPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return goodstobeallocatedPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return goodstobeallocatedPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    goodstobeallocatedPage =
      this.baseMapper.goodstobeallocatedPage(
          search.toPage(this.baseMapper.goodstobeallocatedCount(search)),
          search
        );
    List<Long> recordIds = goodstobeallocatedPage
      .getRecords()
      .stream()
      .map(RequisitionItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return goodstobeallocatedPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return goodstobeallocatedPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    goodstobeallocatedPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return goodstobeallocatedPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 调拨单分页查询结果
   */
  @Override
  public Page<?> goodstobeallocatedPageWithChildSearch(
    RequisitionSearchParamPo search
  ) {
    return appendWithChild(
      goodstobeallocatedPage(search),
      search.toChildSort("requisitionProduct")
    );
  }

  /**
   * 查询待配货最后更新时间
   * @param search 查询条件
   * @return 待配货最后更新时间
   */
  @Override
  public Date goodstobeallocatedLastUpdateTime(
    RequisitionSearchParamPo search
  ) {
    return this.baseMapper.goodstobeallocatedLastUpdateTime(search);
  }

  /**
   * 待调拨
   */
  @Override
  public List<RequisitionItemVo> tobetransferred(
    RequisitionSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.tobetransferred(search);
  }

  /**
   * 待调拨分页
   */
  @Override
  public Page<RequisitionItemVo> tobetransferredPage(
    RequisitionSearchParamPo search
  ) {
    Page<RequisitionItemVo> tobetransferredPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return tobetransferredPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return tobetransferredPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    tobetransferredPage =
      this.baseMapper.tobetransferredPage(
          search.toPage(this.baseMapper.tobetransferredCount(search)),
          search
        );
    List<Long> recordIds = tobetransferredPage
      .getRecords()
      .stream()
      .map(RequisitionItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return tobetransferredPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return tobetransferredPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    tobetransferredPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return tobetransferredPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 调拨单分页查询结果
   */
  @Override
  public Page<?> tobetransferredPageWithChildSearch(
    RequisitionSearchParamPo search
  ) {
    return appendWithChild(
      tobetransferredPage(search),
      search.toChildSort("requisitionProduct")
    );
  }

  /**
   * 查询待调拨最后更新时间
   * @param search 查询条件
   * @return 待调拨最后更新时间
   */
  @Override
  public Date tobetransferredLastUpdateTime(RequisitionSearchParamPo search) {
    return this.baseMapper.tobetransferredLastUpdateTime(search);
  }

  /**
   * 待收货
   */
  @Override
  public List<RequisitionItemVo> waitforreceiving(
    RequisitionSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.waitforreceiving(search);
  }

  /**
   * 待收货分页
   */
  @Override
  public Page<RequisitionItemVo> waitforreceivingPage(
    RequisitionSearchParamPo search
  ) {
    Page<RequisitionItemVo> waitforreceivingPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return waitforreceivingPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return waitforreceivingPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    waitforreceivingPage =
      this.baseMapper.waitforreceivingPage(
          search.toPage(this.baseMapper.waitforreceivingCount(search)),
          search
        );
    List<Long> recordIds = waitforreceivingPage
      .getRecords()
      .stream()
      .map(RequisitionItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return waitforreceivingPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return waitforreceivingPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    waitforreceivingPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return waitforreceivingPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 调拨单分页查询结果
   */
  @Override
  public Page<?> waitforreceivingPageWithChildSearch(
    RequisitionSearchParamPo search
  ) {
    return appendWithChild(
      waitforreceivingPage(search),
      search.toChildSort("requisitionProduct")
    );
  }

  /**
   * 查询待收货最后更新时间
   * @param search 查询条件
   * @return 待收货最后更新时间
   */
  @Override
  public Date waitforreceivingLastUpdateTime(RequisitionSearchParamPo search) {
    return this.baseMapper.waitforreceivingLastUpdateTime(search);
  }

  /**
   * 已完成
   */
  @Override
  public List<RequisitionItemVo> completed(RequisitionSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.completed(search);
  }

  /**
   * 已完成分页
   */
  @Override
  public Page<RequisitionItemVo> completedPage(
    RequisitionSearchParamPo search
  ) {
    Page<RequisitionItemVo> completedPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return completedPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return completedPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    completedPage =
      this.baseMapper.completedPage(
          search.toPage(this.baseMapper.completedCount(search)),
          search
        );
    List<Long> recordIds = completedPage
      .getRecords()
      .stream()
      .map(RequisitionItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return completedPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return completedPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    completedPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return completedPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 调拨单分页查询结果
   */
  @Override
  public Page<?> completedPageWithChildSearch(RequisitionSearchParamPo search) {
    return appendWithChild(
      completedPage(search),
      search.toChildSort("requisitionProduct")
    );
  }

  /**
   * 查询已完成最后更新时间
   * @param search 查询条件
   * @return 已完成最后更新时间
   */
  @Override
  public Date completedLastUpdateTime(RequisitionSearchParamPo search) {
    return this.baseMapper.completedLastUpdateTime(search);
  }

  /**
   * 已撤销
   */
  @Override
  public List<RequisitionItemVo> undone(RequisitionSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.undone(search);
  }

  /**
   * 已撤销分页
   */
  @Override
  public Page<RequisitionItemVo> undonePage(RequisitionSearchParamPo search) {
    Page<RequisitionItemVo> undonePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return undonePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return undonePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    undonePage =
      this.baseMapper.undonePage(
          search.toPage(this.baseMapper.undoneCount(search)),
          search
        );
    List<Long> recordIds = undonePage
      .getRecords()
      .stream()
      .map(RequisitionItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return undonePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return undonePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    undonePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return undonePage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 调拨单分页查询结果
   */
  @Override
  public Page<?> undonePageWithChildSearch(RequisitionSearchParamPo search) {
    return appendWithChild(
      undonePage(search),
      search.toChildSort("requisitionProduct")
    );
  }

  /**
   * 查询已撤销最后更新时间
   * @param search 查询条件
   * @return 已撤销最后更新时间
   */
  @Override
  public Date undoneLastUpdateTime(RequisitionSearchParamPo search) {
    return this.baseMapper.undoneLastUpdateTime(search);
  }
}
